#include <stdio.h>

#include "thread.h"
#include "ipc.h"

static mt_sem_t sem1, *sem2;


static void *thread1_func(void *arg)
{
    char *p = arg;
    
    printf("%s\r\n", p);
    while(1)
    {
        if(mt_sem_take(sem2, MT_WAITING_FOREVER) == MT_EOK)
            printf("sem2 take succeed\r\n");
        else
            printf("sem2 take failed\r\n");
    }
}

static void *thread2_func(void *arg)
{
    char *p = arg;
    
    printf("%s\r\n", p);
    while(1)
    {
        if(mt_sem_take(&sem1, MT_WAITING_FOREVER) == MT_EOK)
        {
            printf("sem1 take succeed\r\n");
            mt_sem_release(sem2);
            mt_sem_release(sem2);
            mt_sem_release(sem2);
        }
        else
            printf("sem1 take failed\r\n");
    }
}

static void *thread3_func(void *arg)
{
    char *p = arg;
    
    printf("%s\r\n", p);
    while(1)
    {
        mt_delay(1000);
        mt_sem_release(&sem1);
    }
}

int sem_test(void)
{
    mt_thread_t *thread1_handle;
    mt_thread_t *thread2_handle;
    mt_thread_t *thread3_handle;
    
    mt_sem_init(&sem1, 
                "sem1", 
                0, 
                10, 
                MT_IPC_FLAG_FIFO);
    sem2 = mt_sem_create("sem2", 
                         0, 
                         10, 
                         MT_IPC_FLAG_FIFO);
    if(sem2 == MT_NULL)
    {
        printf("create sem faied\r\n");
        return -1;
    }
    
    thread1_handle = mt_thread_create("thread1", 
                                      thread1_func, 
                                      "thread1", 
                                      1024, 
                                      12, 
                                      5);
    thread2_handle = mt_thread_create("thread2", 
                                      thread2_func, 
                                      "thread2", 
                                      1024, 
                                      11, 
                                      5);
    thread3_handle = mt_thread_create("thread3", 
                                      thread3_func, 
                                      "thread3", 
                                      1024, 
                                      10, 
                                      5);
    if((thread1_handle == MT_NULL) || (thread2_handle == MT_NULL) || (thread3_handle == MT_NULL))
    {
        printf("create thrtead faied\r\n");
        return -1;
    }
    mt_thread_start(thread1_handle);
    mt_thread_start(thread2_handle);
    mt_thread_start(thread3_handle);
    
    return 0;
}
